﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;

namespace Workflows.Components.Reports
{
    /// <summary>
    /// 
    /// </summary>
    public class DataSetWriter
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="ds"></param>
        public static void WriteDataSet(string filePath, DataSet ds)
        {
            XmlTextWriter writer = new XmlTextWriter(filePath,Encoding.Default);
            writer.WriteStartElement("Tables");
            foreach(DataTable dt in ds.Tables)
            {
                writer.WriteStartElement(dt.TableName);
                writer.WriteStartElement("Cols");
                int colIdx = 0;
                foreach(DataColumn col in dt.Columns)
                {
                    writer.WriteStartElement("Col");
                    writer.WriteAttributeString("ColumnName",col.ColumnName);
                    writer.WriteAttributeString("DataType",col.DataType.ToString());
                    writer.WriteAttributeString("Ordinal",colIdx.ToString());
                    writer.WriteEndElement();//Col
                    colIdx++;
                }
                writer.WriteStartElement("Rows");
                foreach(DataRow dr in dt.Rows)
                {
                    writer.WriteStartElement("Row");
                    for(int i=0;i<dt.Columns.Count;i++)
                    {
                        if(dr[i]!=null && dr[i]!=DBNull.Value)
                        {
                            writer.WriteAttributeString("Ordinal",i.ToString());
                            writer.WriteAttributeString("Value", dr[i].ToString());
                        }
                    }
                    writer.WriteEndElement();//Row
                }
                writer.WriteEndElement();//Rows
                writer.WriteEndElement();//cols
                writer.WriteEndElement();//table 
            }
            writer.WriteEndElement();//Tables

            writer.Flush();
            writer.Close();
        }
    }
}
